<!--
 * @Author: wang_zhongwang wang_zhongwang@uxsino.com
 * @Date: 2023-03-24 17:22:17
 * @LastEditors: wang_zhongwang wang_zhongwang@uxsino.com
 * @LastEditTime: 2023-03-24 17:22:17
 * @Description: 接触网腕臂偏移量监测（DPMT）
-->
<template>
  <div class="content">
    <div class="page-title">
      <div class="left">
        <div class="bar" />
        <span class="title">实时监控</span>
      </div>
      <div class="right" @click="goBack">
        <img src="@/assets/images/c6/back.png" class="icon">
        <span class="back">返回</span>
      </div>
    </div>
    <div class="main">
      <div class="row1">
        <el-card class="col1">
          <div slot="header" style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;background-color: #ffffff;">
            <div style="display:flex;align-items: center">
              <div class="content-header-vertical-bar" />
              <span style="margin-right:7px; font-weight: 600;font-size: 14px;">实时数据</span>
            </div>
          </div>
          <div class="cardMain">
            <div ref="charts1" class="chartBox" />
            <div class="time">更新时间: {{ moment(myqueenDataLast.event_time).format('YYYY-MM-DD HH:mm:ss') }}</div>
          </div>
        </el-card>
        <el-card class="col2">
          <div slot="header" style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;background-color: #ffffff;">
            <div style="display:flex;align-items: center">
              <div class="content-header-vertical-bar" />
              <span style="margin-right:7px;font-weight: 600;font-size: 14px;">近期数据</span>
            </div>
            <el-button type="primary" size="mini" icon="el-icon-download" @click="getImg2">导出图片</el-button>
          </div>
          <div class="cardMain">
            <div ref="charts2" class="chartBox" />
          </div>
        </el-card>
      </div>
      <div class="row2">
        <el-card class="col1">
          <div slot="header" style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;background-color: #ffffff;">
            <div style="display:flex;align-items: center">
              <div class="content-header-vertical-bar" />
              <span style="margin-right:7px;font-weight: 600;font-size: 14px;">数据聚合查询</span>
            </div>
            <el-button type="primary" size="mini" icon="el-icon-download" @click="getImg3">导出图片</el-button>
          </div>
          <div class="cardMain">
            <el-form ref="listQuery" :inline="true" :model="listQuery" class="form">
              <el-form-item prop="fieldName" :rules="{ required: true, message: '属性不能为空', trigger: 'change' }" class="select">
                <el-select v-model="listQuery.fieldName" placeholder="选择属性">
                  <el-option v-for="item in fieldNameOption" :key="item.name" :label="item.description" :value="item.name" />
                </el-select>
              </el-form-item>
              <!--              <el-form-item prop="type" :rules="{ required: true, message: '类型不能为空', trigger: 'change' }" class="select">-->
              <!--                <el-select v-model="listQuery.type" placeholder="类型">-->
              <!--                  <el-option v-for="item in typeOption" :key="item.value" :label="item.label" :value="item.value" />-->
              <!--                </el-select>-->
              <!--              </el-form-item>-->
              <!--              <el-form-item v-if="listQuery.type=='2'" prop="aggregate" :rules="{ required: true, message: '聚合函数不能为空', trigger: 'change' }" class="select">-->
              <!--                <el-select v-model="listQuery.aggregate" placeholder="聚合函数">-->
              <!--                  <el-option v-for="item in aggregateOption" :key="item.value" :label="item.label" :value="item.value" />-->
              <!--                </el-select>-->
              <!--              </el-form-item>-->
              <!--              <el-form-item v-if="listQuery.type=='2'" prop="interval" :rules="{ required: true, message: '时间间隔不能为空', trigger: 'change' }" class="select">-->
              <!--                <el-select v-model="listQuery.interval" placeholder="interval">-->
              <!--                  <el-option v-for="item in intervalOption" :key="item.value" :label="item.label" :value="item.value" />-->
              <!--                </el-select>-->
              <!--              </el-form-item>-->
              <el-form-item v-if="listQuery.type == '0' || listQuery.type == '2' || listQuery.type == '3'" prop="startTime" :rules="{ required: true, message: '选择开始时间', trigger: 'change' }" class="select-date">
                <el-date-picker v-model="listQuery.startTime" type="datetime" placeholder="选择开始时间" style="width: 167px" />
              </el-form-item>
              <el-form-item v-if="listQuery.type == '0' || listQuery.type == '2' || listQuery.type == '3'" prop="endTime" :rules="{ required: true, message: '选择结束时间', trigger: 'change' }" class="select-date">
                <el-date-picker v-model="listQuery.endTime" type="datetime" placeholder="选择结束时间" style="width: 167px" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getVisualizeData">查询</el-button>
              </el-form-item>
            </el-form>
            <div ref="charts3" class="chartBox" />
          </div>
        </el-card>
        <el-card class="col2">
          <div slot="header" style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;background-color: #ffffff;">
            <div style="display:flex;align-items: center">
              <div class="content-header-vertical-bar" />
              <span style="margin-right:7px;font-weight: 600;font-size: 14px;">报警数据</span>
            </div>
          </div>
          <div class="cardMain">
            <el-table :key="alarm.tableKey" v-loading="alarm.listLoading" :data="alarm.list" border fit highlight-current-row tooltip-effect="dark" class="table">
              <el-table-column align="center" label="时间" prop="alarmTime" :show-overflow-tooltip="true" />
              <el-table-column align="center" label="名称" prop="alarmName" :show-overflow-tooltip="true" />
              <el-table-column align="center" label="偏移量" prop="dataMap.pos_val" :show-overflow-tooltip="true" />
            </el-table>
            <div class="page-box">
              <pagination :total="alarm.total" :pager-count="5" :page.sync="alarm.alarmListQuery.page" :size.sync="alarm.alarmListQuery.size" @pagination="getRuleAlarmList" />
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>
<script>
import echarts from 'echarts'
import Queue from '@/utils/queue'
var myqueen = new Queue()
import moment from 'moment'
import { fontSize } from '@/utils'
import { getListByProductIdentification } from '@/api/cms/winglinks/product/properties'
import { getVisualizeData, getLastNumData } from '@/api/cms/winglinks/tdengine'
import { getRuleAlarmPageList } from '@/api/cms/monitor/event'
export default {
  data() {
    return {
      // 数据队列
      myqueenData: [],
      myqueenDataLast: {},
      newQueenData: {
        event_time: [],
        volt_level: [],
        pos_val: []
      },
      // 数据聚合查询下拉框options
      fieldNameOption: [],
      typeOption: [{ label: '历史数据', value: '0' }, { label: '实时数据', value: '1' }, { label: '聚合数据', value: '2' }],
      aggregateOption: [{ label: '合计', value: 'sum' }, { label: '最大值', value: 'max' }, { label: '最小值', value: 'min' }, { label: '平均值', value: 'avg' }],
      intervalOption: [{ label: '一秒', value: '1s' }, { label: '一分钟', value: '1m' }, { label: '一小时', value: '1h' }, { label: '一天', value: '1d' }, { label: '一个月', value: '1n' }, { label: '一年', value: '1y' }],
      // 数据聚合查询查询参数
      listQuery: {
        num: 7, // 查询个数
        interval: '1d', // 间隔
        fieldName: null, // 属性
        type: '3', // 类型
        aggregate: null, // 聚合函数
        dataBaseName: 'winglinks', // 数据库名称
        tableName: '', // 表名称
        startTime: moment().subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss'), // 开始时间
        endTime: moment().format('YYYY-MM-DD HH:mm:ss') // 结束时间
      },
      // 报警信息参数
      alarm: {
        height: 0,
        tableKey: 0,
        list: [],
        current: 1,
        total: 0,
        listLoading: false,
        alarmListQuery: {
          page: 1,
          size: 5,
          deviceIdentification: null
        }
      },
      // 路由参数
      voh_config: {
        deviceIdentification: '',
        productIdentification: '',
        deviceType: '',
        benchmark: 0
      }
    }
  },
  watch: {
  },
  created() {
    // this.connectWS()
  },

  activated() {
    // 获取路由参数
    this.voh_config = Object.assign(this.voh_config, JSON.parse(this.$route.query.row))
    this.connectWS()
    // 绑定监听
    window.addEventListener('beforeunload', (e) => this.closeWebSocket(e))
    this.getPropertiesOptions()
    this.getRuleAlarmList()
  },
  methods: {
    getRuleAlarmList() {
      this.alarm.alarmListQuery.deviceIdentification = this.voh_config.deviceIdentification
      this.alarm.listLoading = true
      getRuleAlarmPageList(this.alarm.alarmListQuery).then(res => {
        this.alarm.list = res.data.records
        this.alarm.total = res.data.total
        this.alarm.listLoading = false
      }).catch(() => {
        this.alarm.listLoading = false
      })
    },
    getLastData() {
      this.listQuery.tableName = this.generateTableName()
      getLastNumData(this.listQuery).then(res => {
        if (res.data) {
          res.data.forEach(item => {
            if (item != null) {
              myqueen.enqueue(item)
            }
            if (myqueen.size() > 8) {
              myqueen.dequeue()
            }
            this.myqueenData = JSON.parse(JSON.stringify(myqueen.show()))
            this.myqueenDataLast = this.myqueenData[this.myqueenData.length - 1]
            this.newQueenData = {
              event_time: [],
              volt_level: [],
              pos_val: []
            }
            this.myqueenData.forEach(element => {
              this.newQueenData.event_time.push(moment(element.event_time).format('YYYY-MM-DD HH:mm:ss'))
              this.newQueenData.volt_level.push(element.volt_level)
              this.newQueenData.pos_val.push((element.pos_val - this.voh_config.benchmark).toFixed(3))
            })
          })
        }
        this.getcharts1(this.myqueenDataLast)
        this.getcharts2(this.newQueenData)
      })
    },
    getVisualizeData() {
      this.listQuery.tableName = this.generateTableName()
      this.$refs['listQuery'].validate((valid) => {
        if (valid) {
          var xData = []
          var yData = []
          getVisualizeData(this.listQuery).then(res => {
            console.log(res)
            if (res.data) {
              if (this.listQuery.fieldName === 'pos_val') {
                var data = {
                  avg: [],
                  min: [],
                  max: [],
                  time: res.data.time
                }
                res.data.avg.forEach(a => {
                  data.avg.push((a - this.voh_config.benchmark).toFixed(3))
                })
                res.data.min.forEach(a => {
                  data.min.push((a - this.voh_config.benchmark).toFixed(3))
                })
                res.data.max.forEach(a => {
                  data.max.push((a - this.voh_config.benchmark).toFixed(3))
                })
                this.getcharts3(data)
              } else {
                this.getcharts3(res.data)
              }
            }
          })
        }
      })
    },

    generateTableName() {
      var tableName = this.voh_config.deviceType + '_' + this.voh_config.productIdentification + '_' + 'analog_' + this.voh_config.deviceIdentification
      return tableName
    },

    getPropertiesOptions() {
      getListByProductIdentification(this.voh_config.productIdentification).then(res => {
        let index = 0
        res.data.forEach(item => {
          this.fieldNameOption = res.data
          if (index === 0) { this.listQuery.fieldName = item.name }
          index++
        })
        this.getLastData()
        this.getVisualizeData()
      })
    },
    getcharts1(data) {
      const myChart = echarts.init(this.$refs.charts1)
      // const option = {
      //   tooltip: {
      //     formatter: '{a} : {c}mm'
      //   },
      //   series: [
      //     {
      //       name: '位移',
      //       type: 'gauge',
      //       min: -1000,
      //       max: 1000,
      //       radius: '95%', // 参数:number, string。 仪表盘半径,默认 75% ，可以是相对于容器高宽中较小的一项的一半的百分比，也可以是绝对的数值。
      //       center: ['50%', '50%'], // 仪表盘位置(圆心坐标)
      //       startAngle: 225, // 仪表盘起始角度,默认 225。圆心 正右手侧为0度，正上方为90度，正左手侧为180度。
      //       endAngle: -45, // 仪表盘结束角度,默认 -45
      //       detail: {
      //         formatter: '{value}mm',
      //         textStyle: {
      //           fontSize: 15
      //         }},
      //       axisTick: { // 刻度(线)样式。
      //         show: true, // 是否显示刻度(线),默认 true。
      //         length: 8, // 刻度线长。支持相对半径的百分比,默认 8。
      //         lineStyle: { // 刻度线样式。
      //           color: '#eee', // 线的颜色,默认 #eee。
      //           opacity: 1, // 图形透明度。支持从 0 到 1 的数字，为 0 时不绘制该图形。
      //           width: 1, // 线度,默认 1。
      //           type: 'dotted', // 线的类型,默认 solid。 此外还有 dashed,dotted
      //           shadowBlur: 10, // (发光效果)图形阴影的模糊大小。该属性配合 shadowColor,shadowOffsetX, shadowOffsetY 一起设置图形的阴影效果。
      //           shadowColor: '#fff' // 阴影颜色。支持的格式同color。
      //         }
      //       },
      //       data: [
      //         {
      //           value: data.pos_val,
      //           name: '位移'
      //         }
      //       ]
      //     }
      //   ]
      // }
      const option = {
        tooltip: {
          formatter: '{a} : {c}°'
        },
        grid: {
          right: '5%',
          left: '5%',
          top: '1%',
          bottom: '5%',
          borderWidth: 1
        },
        xAxis: {
          show: false,
          type: 'category',
          data: ['Mon']
        },
        yAxis: {
          show: false,
          type: 'value'
        },
        series: [
          {
            name: '位移',
            type: 'gauge',
            radius: '70%',
            detail: {
              offsetCenter: [0, '70%'],
              formatter: '{value}°',
              textStyle: {
                color: '#409EFF',
                // 字体大小
                fontSize: fontSize(0.2)
              }
            },
            min: -1000,
            max: 1000,
            splitNumber: 4,
            startAngle: 225,
            endAngle: -45,
            zlevel: 0,
            data: [
              {
                value: (data.pos_val - this.voh_config.benchmark).toFixed(3)
              }
            ],
            legend: {
              padding: 0,
              margin: 0
            },
            pointer: {
              show: true,
              length: '70%',
              radius: '50%',
              width: 3 // 指针粗细
            },
            itemStyle: {
              color: '#2673B8'
            },
            markLine: {
              precision: 2
            },
            axisTick: {
              show: false,
              splitNumber: 5,
              lineStyle: {
                width: 2
              },
              length: -8
            }, // 刻度样式
            splitLine: {
              show: true,
              length: -8,
              lineStyle: {
                color: '#BAE7FF' // 用颜色渐变函数不起作用
              }
            }, // 分隔线样式
            axisLabel: {
              show: true,
              distance: -20,
              textStyle: {
                color: '#969FB5'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                width: 25,
                color: [
                  [
                    1,
                    new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                      {
                        offset: 0,
                        color: '#68F6FF'
                      },
                      {
                        offset: 0.25,
                        color: '#68EDFF'
                      },
                      {
                        offset: 0.75,
                        color: '#2EA7FF'
                      },
                      {
                        offset: 1,
                        color: '#0168FF'
                      }
                    ])
                  ]
                ]
              }
            }
          },
          {
            name: '小圆形',
            type: 'pie',
            hoverAnimation: false,
            legendHoverLink: false,
            zlevel: 0,
            radius: ['0%', '8%'],
            tooltip: {
              show: false
            },
            z: 10,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: false
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: [
              {
                value: 100,
                name: '2',
                itemStyle: {
                  normal: {
                    color: 'rgba(102, 157, 174, 0.4)'
                  }
                }
              }
            ]
          }
        ]
      }
      myChart.setOption(option)
    },
    // 清空当前实例
    clearHander() {
      // 清空当前实例，会移除实例中所有的组件和图表。
      const myChart = echarts.init(this.$refs.charts1)
      myChart.clear()
    },
    getcharts2(newQueenData) {
      const myChart = echarts.init(this.$refs.charts2)
      const option = {
        grid: {
          left: '8%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          showContent: true,
          formatter: '{a} <br/>{b} : {c}°'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: newQueenData.event_time,
          axisLabel: {
            interval: 0,
            rotate: 40,
            formatter: function(params) { // x轴时间换行问题
              var newParamsName = ''
              var paramsNameNumber = params.length
              var provideNumber = 11
              var rowNumber = Math.ceil(paramsNameNumber / provideNumber)
              if (paramsNameNumber > provideNumber) {
                for (var p = 0; p < rowNumber; p++) {
                  var tempStr = ''
                  var start = p * provideNumber
                  var end = start + provideNumber
                  if (p == rowNumber - 1) {
                    tempStr = params.substring(start, paramsNameNumber)
                  } else {
                    tempStr = params.substring(start, end) + '\n'
                  }
                  newParamsName += tempStr
                }
              } else {
                newParamsName = params
              }
              return newParamsName
            }
          }
        },
        yAxis: {
          type: 'value',
          splitLine: { show: true }
          // axisLine: { onZero: false },
          // boundaryGap: true
        },
        series: [
          {
            name: '近期数据',
            data: newQueenData.pos_val,
            type: 'line',
            itemStyle: { normal: { label: { show: true }}},
            areaStyle: {}
          }
        ],
        color: '#93ccff'
      }
      myChart.clear()
      myChart.setOption(option)
    },
    getcharts3(dataMap) {
      const myChart = echarts.init(this.$refs.charts3)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        // 坐标轴位置属性
        grid: {
          top: '15%',
          left: '8%',
          right: '8%',
          bottom: '20%'
        },
        color: ['#b620e0', '#f2bf24', '#33bbff'],
        legend: [
          {
            data: ['最大值', '最小值', '平均值'], // 这里要与下面的name对应
            right: '40',
            icon: 'circle',
            itemWidth: 10, // 设置宽度
            itemHeight: 15 // 设置高度
          }
        ],
        xAxis: [
          {
            type: 'category',
            axisLabel: {
              interval: 0,
              rotate: 40,
              formatter: function(params) { // x轴时间换行问题
                var newParamsName = ''
                var paramsNameNumber = params.length
                var provideNumber = 11
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber)
                if (paramsNameNumber > provideNumber) {
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = ''
                    var start = p * provideNumber
                    var end = start + provideNumber
                    if (p === rowNumber - 1) {
                      tempStr = params.substring(start, paramsNameNumber)
                    } else {
                      tempStr = params.substring(start, end) + '\n'
                    }
                    newParamsName += tempStr
                  }
                } else {
                  newParamsName = params
                }
                return newParamsName
              }
            },
            data: dataMap.time,
            axisPointer: {
              type: 'shadow'
            },
            axisLine: {
              lineStyle: {
                width: 1 // 这里是为了突出显示加上的
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '',
            axisLabel: {
              formatter: '{value}',
              textStyle: {
                fontSize: 14
              }
            },
            splitLine: {
              show: false
            },

            axisLine: {
              lineStyle: {
                width: 1 // 这里是为了突出显示加上的
              }
            }
          },
          {
            type: 'value',
            name: '',
            position: 'right',
            splitNumber: 5,
            axisLabel: {
              formatter: '{value}',
              textStyle: {
                color: '#606266',
                fontSize: 14
              }
            },
            splitLine: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: 'rgba(192, 209, 225, 1)',
                width: 1 // 这里是为了突出显示加上的
              }
            }
          }
        ],
        series: [
          {
            name: '最大值',
            type: 'bar',
            data: dataMap.max,
            barWidth: 10
          },
          {
            name: '最小值',
            type: 'bar',
            data: dataMap.min,
            barWidth: 10
          },
          {
            name: '平均值',
            type: 'line',
            yAxisIndex: 1,
            data: dataMap.avg,
            itemStyle: {
              normal: {
                areaStyle: {
                  type: 'default',
                  // 渐变色实现===
                  color: new echarts.graphic.LinearGradient(
                    0,
                    0,
                    0,
                    1,
                    // 三种由深及浅的颜色
                    [
                      {
                        offset: 0,
                        color: 'rgba(102, 255, 255, 0.17)'
                      },
                      {
                        offset: 1,
                        color: 'rgba(102, 255, 255, 0.17)'
                      }
                    ]
                  )
                },
                lineStyle: {
                  // 线的颜色
                  color: '#66FFDA'
                },
                // 以及在折线图每个日期点顶端显示数字
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: 'white'
                  }
                }
              }
            }
          }
        ]
      }
      myChart.clear()
      myChart.setOption(option)
    },
    // getcharts3(xData, yData) {
    //   const myChart = echarts.init(this.$refs.charts3)
    //   const option = {
    //     grid: {
    //       left: '5%',
    //       right: '4%',
    //       bottom: '3%',
    //       top: '10%',
    //       containLabel: true
    //     },
    //     tooltip: {
    //       trigger: 'axis',
    //       showContent: true,
    //       formatter: '{a} <br/>{b} : {c}'
    //     },
    //     xAxis: {
    //       type: 'category',
    //       boundaryGap: false,
    //       data: xData,
    //       axisLabel: {
    //         interval: 0,
    //         rotate: 40,
    //         formatter: function(params) { // x轴时间换行问题
    //           var newParamsName = ''
    //           var paramsNameNumber = params.length
    //           var provideNumber = 11
    //           var rowNumber = Math.ceil(paramsNameNumber / provideNumber)
    //           if (paramsNameNumber > provideNumber) {
    //             for (var p = 0; p < rowNumber; p++) {
    //               var tempStr = ''
    //               var start = p * provideNumber
    //               var end = start + provideNumber
    //               if (p == rowNumber - 1) {
    //                 tempStr = params.substring(start, paramsNameNumber)
    //               } else {
    //                 tempStr = params.substring(start, end) + '\n'
    //               }
    //               newParamsName += tempStr
    //             }
    //           } else {
    //             newParamsName = params
    //           }
    //           return newParamsName
    //         }
    //       }
    //     },
    //     yAxis: {
    //       type: 'value',
    //       splitLine: { show: true }
    //       // axisLine: { onZero: false },
    //       // boundaryGap: true
    //     },
    //     series: [
    //       {
    //         name: '数据',
    //         data: yData,
    //         type: 'line',
    //         itemStyle: { normal: { label: { show: true }}},
    //         areaStyle: {}
    //       }
    //     ],
    //     color: '#879bd7'
    //   }
    //   myChart.clear()
    //   myChart.setOption(option)
    // },
    connectWS: function() {
      if (typeof WebSocket === 'undefined') {
        this.$message({
          type: 'warning',
          message: '当前浏览器不支持WebSocket',
          showClose: true
        })
      } else {
        const url = process.env.VUE_APP_C6_WEBSOCKET_API + this.voh_config.deviceIdentification + '?req=ok'
        console.log(url)
        this.websocket = new WebSocket(url)
        this.websocket.onopen = this.open
        this.websocket.onerror = this.error
        this.websocket.onmessage = this.message
        this.websocket.onclose = this.close
      }
    },
    open: function() {
      console.log('WebSocket Connected successfully~')
    },
    error: function(e) {
      console.log('WebSocket Error: ' + JSON.stringify(e))
    },
    message: function(msg) {
      console.log('WebSocket Message: ', msg)
      if (msg.data != null) {
        const data = JSON.parse(msg.data)
        console.log('data: ', data)
        console.log('fieldValue: ', data.fieldValue)
        myqueen.enqueue(data.fieldValue)
      }
      if (myqueen.size() > 8) {
        myqueen.dequeue()
      }
      this.myqueenData = JSON.parse(JSON.stringify(myqueen.show()))
      this.myqueenDataLast = this.myqueenData[this.myqueenData.length - 1]
      this.newQueenData = {
        event_time: [],
        volt_level: [],
        pos_val: []
      }
      this.myqueenData.forEach(element => {
        this.newQueenData.event_time.push(moment(element.event_time).format('YYYY-MM-DD HH:mm:ss'))
        this.newQueenData.volt_level.push(element.volt_level)
        this.newQueenData.pos_val.push(element.pos_val)
      })
      this.getcharts1(this.myqueenDataLast)
      this.getcharts2(this.newQueenData)
    },
    send: function(params) {
      this.websocket.send(params)
    },
    close: function() {
      console.log('WebSocket Disconnected!')
      setTimeout(() => {
        console.log('WebSocket reconnecting...')
        this.connectWS(this.thisCity)
      }, 3000)
    },
    closeWebSocket: function() {
      console.log('Closing websocket...')
      if (this.websocket) {
        this.websocket.close()
      }
    },

    // 刷新页面是关闭WebSocket连接
    beforeUnmount() {
      window.removeEventListener('beforeunload', (e) => this.closeWebSocket(e))
    },

    getImg2() {
      const myChart = echarts.init(this.$refs.charts2)
      const imgName = '近期数据'
      this.getImage('png', myChart, imgName)
    },

    getImg3() {
      const myChart = echarts.init(this.$refs.charts3)
      const imgName = '数据聚合图片'
      this.getImage('png', myChart, imgName)
    },

    // 保存图片
    getImage(imgType, myChart, imgName) {
      var url = myChart.getConnectedDataURL({
        pixelRatio: 2, // 导出的图片分辨率比率,默认是1
        backgroundColor: '#fff', // 图表背景色
        excludeComponents: [
          // 保存图表时忽略的工具组件,默认忽略工具栏
          'toolbox'
        ],
        type: imgType // 图片类型支持png和jpeg
      })
      var $a = document.createElement('a')
      var type = imgType
      $a.download = imgName
      $a.target = '_blank'
      $a.href = url
      // Chrome and Firefox
      if (typeof MouseEvent === 'function') {
        var evt = new MouseEvent('click', {
          view: window,
          bubbles: true,
          cancelable: false
        })
        $a.dispatchEvent(evt)
      } else {
        var base64 = {
          dataURL: url,
          type: imgType,
          ext: imgType
        }
        var blob = this.convertBase64UrlToBlob(base64)
        // 下载
        window.navigator.msSaveBlob(
          blob,
          myChart.getOption().title[0].text + '.' + imgType
        )
      }
    },
    convertBase64UrlToBlob(base64) {
      var parts = base64.dataURL.split(';base64,')
      var contentType = parts[0].split(':')[1]
      var raw = window.atob(parts[1])
      var rawLength = raw.length
      var uInt8Array = new Uint8Array(rawLength)
      for (var i = 0; i < rawLength; i++) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },
    // 返回上一页
    goBack() {
      this.$router.push({ path: '/cms/device-data/device', query: null })
    }
  }
}
</script>
<style lang="scss" scoped>
  /deep/.el-card__header{
    height: 60px;
    background-color: #ffffff;
  }
  /deep/.el-card__body {
    padding: 0;
    width: 100%;
    height: calc(100% - 60px);
    border: 0;
  }
  .content {
    width: 100%;
    height: 96%;
    background: #f1f4fb;
    padding: 5px 15px 15px 15px;
    overflow-y: auto;
  }
  .page-title{
    height: 5%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    .left{
      height: 100%;
      align-items: center;
      display: flex;
      flex-direction: row;
      margin-left: 3px;
      .bar{
        width: 7px;
        height: 70%;
        border-radius: 2px;
        background: #409EFF;
        margin-right: 10px;
      }
      .title{
        font-weight: 600;
        font-size: 18px;
        color: #303133;
      }
    }
    .right{
      height: 100%;
      align-items: center;
      display: flex;
      flex-direction: row;
      line-height: 100%;
      .icon{
        margin-right: 5px;
        height: 60%;
        width: auto;
      }
      .back{
        font-size: 16px;
        color: #409EFF;
      }

    }
  }
  .main {
    width: 100%;
    height: 100%;
    display: flex;
    padding: 15px;
    border-radius: 10px;
    box-shadow: 0px 0px 10px 5px rgba(0, 47, 138, 0.04);
    background-color: #ffffff;
    flex-direction: column;
    justify-content: space-between;
  }

  .row1{
    width:100%;
    height:48%;
    display: flex;
    justify-content: space-between;
    .col1{
      height: 100%;
      width: 25%;
      background-color: #ffffff;
      box-shadow: 0px 0px 10px 5px rgba(0, 47, 138, 0.04);
      border-radius: 12px;
      .content-header-vertical-bar {
        width: 7px;
        height: 26px;
        background: #409eff;
        border-radius: 4px;
        margin-right: 13px;
      }
      .cardMain{
        width: 100%;
        height: 100%;
        position: relative;
        .chartBox{
          width: 100%;
          height: 100%;
        }
        .time{
          position: absolute;
          left: 0;
          bottom: 0;
          width: 100%;
          height: 12%;
          color: #409EFF;
          font-size: 20px;
          display: flex;
          flex-direction: row;
          justify-content: center;
        }
      }
    }
    .col2{
      height: 100%;
      width: 74%;
      background-color: #ffffff;
      box-shadow: 0px 0px 10px 5px rgba(0, 47, 138, 0.04);
      border-radius: 12px;
      .content-header-vertical-bar {
        width: 7px;
        height: 26px;
        background: #409eff;
        border-radius: 4px;
        margin-right: 13px;
      }
      .cardMain{
        width: 100%;
        height: 100%;
        .chartBox{
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .row2{
    width:100%;
    min-height:51%;
    background-color: #ffffff;
    display: flex;
    justify-content: space-between;
    .col1{
      height: 100%;
      width: 64%;
      background-color: #ffffff;
      box-shadow: 0px 0px 10px 5px rgba(0, 47, 138, 0.04);
      border-radius: 12px;
      .content-header-vertical-bar {
        width: 7px;
        height: 26px;
        background: #409eff;
        border-radius: 4px;
        margin-right: 13px;
      }
      .cardMain{
        width: 100%;
        height: 100%;
        .form{
          height: 50px;
          padding: 8px 5px;
          .select{
            width: 110px;
            margin-right: 5px;
          }
          .select-date{
            margin-right: 5px;
          }
        }
        .chartBox{
          width: 100%;
          height: calc(100% - 50px);
        }
      }
    }
    .col2{
      height: 100%;
      width: 35%;
      background-color: #ffffff;
      box-shadow: 0px 0px 10px 5px rgba(0, 47, 138, 0.04);
      border-radius: 12px;
      .content-header-vertical-bar {
        width: 7px;
        height: 26px;
        background: #409eff;
        border-radius: 4px;
        margin-right: 13px;
      }
      .cardMain{
        width: 100%;
        height: 100%;
        .table{
          height: calc(100% - 40px);
          width: 100%;
        }
        .page-box{
          height: 40px;
          width: 100%;
        }
      }
    }
  }
</style>
